package com.example.imchat.controller.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.example.imchat.R;
import com.example.imchat.controller.activity.AddContactActivity;
import com.example.imchat.controller.activity.ChatActivity;
import com.example.imchat.controller.activity.GroupListActivity;
import com.example.imchat.controller.activity.InviteInfoActivity;
import com.example.imchat.model.Model;
import com.example.imchat.model.bean.UserInfo;
import com.example.imchat.utils.Constant;
import com.example.imchat.utils.SpUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*联系人页面*/
public class ContactListFragment extends EaseContactListFragment {
    private ImageView contact_invite;
    private LocalBroadcastManager mLBM;
    private  LinearLayout contact_friend_add;
    private LinearLayout  contact_group;
    private  String mHxid;
    private BroadcastReceiver ContactInviteChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //更新红点显示
            contact_invite.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);

        }
    };
    //联系人列表得广播
    private BroadcastReceiver ContactChangeReceiver = new BroadcastReceiver() {
        //刷新联系人的列表
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshContact();
        }
    };
    private BroadcastReceiver GroupChangeReceiver =new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //显示红点
            contact_invite.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);
        }
    };


    @Override
    protected void initView() {
        super.initView();
        //contact 加号
          titleBar.setRightImageResource(R.drawable.titlebar_add);

        //添加头布局
        View headerView = View.inflate(getActivity(),R.layout.header_fragment_contact,null);
        listView.addHeaderView(headerView);

        //获取红点对象
        contact_invite = (ImageView)headerView.findViewById(R.id.contact_invite);
        //获取群主对象
        contact_group = headerView.findViewById(R.id.contact_group);
        //获取页面对象
        contact_friend_add =(LinearLayout) headerView.findViewById(R.id.contact_friend_add);

        //设置listview条目的点击事件
        setContactListItemClickListener(new EaseContactListItemClickListener() {
            @Override
            public void onListItemClicked(EaseUser user) {
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                //传递参数
                intent.putExtra(EaseConstant.EXTRA_USER_ID,user.getUsername());
                startActivity(intent);
            }
        });

    }

    @Override
    protected void setUpView() {
        super.setUpView();

        //添加按钮的点击事件处理
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddContactActivity.class);
                startActivity(intent);
            }
        });

        //初始化红点显示
        boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE,false);
        contact_invite.setVisibility(isNewInvite? View.VISIBLE:View.GONE);

        //跳转到群组信息界面
        contact_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到群聊界面
                Intent intent = new Intent(getActivity(), GroupListActivity.class);
                startActivity(intent);
            }
        });

        //新朋友的点击事件  点击 红点消失
        contact_friend_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                contact_invite.setVisibility(View.GONE);
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,false);

                //跳转到邀请界面
                Intent intent = new Intent(getActivity(), InviteInfoActivity.class);
                startActivity(intent);
            }
        });

        //注册广播
        mLBM = LocalBroadcastManager.getInstance(getActivity());
        mLBM.registerReceiver( ContactInviteChangeReceiver, new IntentFilter( Constant.CONTACT_INVITE_CHANGED ) );
        mLBM.registerReceiver( ContactChangeReceiver, new IntentFilter( Constant.CONTACT_CHANGED ) );

        mLBM.registerReceiver(GroupChangeReceiver,new IntentFilter(Constant.GROUP_INVITE_CHANGED));
        //从环信服务器获取所有联系人
        getContactFromHxServer();

        //绑定listvierw和contextmenu
        registerForContextMenu(listView);
    }
    @Override
    public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        //获取环信id
        int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
        EaseUser easeUser = (EaseUser) listView.getItemAtPosition(position);
        mHxid = easeUser.getUsername();
        //添加布局的方法
        getActivity().getMenuInflater().inflate(R.menu.delete,menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.contact_delete){
            //删除操作
            deleteContact();
            return true;
        }
        return super.onContextItemSelected(item);
    }
    //删除联系人操作 环信服务器 —— 本地数据库 —— 内存更新
    private void deleteContact() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {

                try {
                    EMClient.getInstance().contactManager().deleteContact(mHxid);
                    //本地数据库的更新
                    Model.getInstance().getDbManager().getContactTableDao().deleteContactByHxid(mHxid);
                    //判断 防止报空指针
                    if (null == getActivity())
                    {
                        return;
                    }
                    //内存更新  刷新界面显示
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(),"删除"+mHxid+"成功",Toast.LENGTH_SHORT).show();
                            refreshContact();
                        }
                    });
                } catch (HyphenateException e) {
                    if (null == getActivity())
                    {
                        return;
                    }
                    //内存更新  刷新界面显示
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(),"删除"+mHxid+"失败"+e,Toast.LENGTH_SHORT).show();
                            refreshContact();
                        }
                    });
                }
            }
        });
    }

    //从环信服务器获取所有联系人
    private void getContactFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取了所有好友的环信id
                    List<String> hxids = EMClient.getInstance().contactManager().getAllContactsFromServer();

                    //校验
                    if (null !=hxids&& hxids.size()>=0){
                        List<UserInfo> contacts = new ArrayList<>();
                        //转换
                        for (String hxid : hxids){
                            UserInfo userInfo = new UserInfo(hxid);
                            contacts.add(userInfo);
                        }
                        //保存好友信息到本地数据库
                        Model.getInstance().getDbManager().getContactTableDao().saveContacts(contacts,true);
                        //判断 防止报空指针
                        if (null == getActivity())
                        {
                            return;
                        }
                        //刷新页面
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshContact();
                            }
                        });


                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });

    }
        //联系人的刷新方法
    private void refreshContact() {

        //获取数据
        List<UserInfo> contacts = Model.getInstance().getDbManager().getContactTableDao().getContacts();
        if (contacts != null && contacts.size()>=0){
            //设置数据
            Map<String, EaseUser> contactsMap = new HashMap<>();
            //转换
            for (UserInfo contact:contacts){
                EaseUser easeUser = new EaseUser(contact.getHxid());
                contactsMap.put(contact.getHxid(),easeUser);
            }
            setContactsMap(contactsMap);
            //刷新页面
            refresh();

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //关闭广播
        mLBM.unregisterReceiver(ContactInviteChangeReceiver);
        mLBM.unregisterReceiver(ContactChangeReceiver);
        mLBM.unregisterReceiver(GroupChangeReceiver);

    }
}
